package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;

/**
 * @author zcf
 */
@Service
@Slf4j
public class DishServiceImpl implements DishService {

    @Resource
    private DishMapper dishMapper;

    @Resource
    private SetmealMapper setmealMapper;
    @Resource
    private DishFlavorMapper dishFlavorMapper;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void save(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        dish.setStatus(StatusConstant.DISABLE);
        //新增菜品
        dishMapper.save(dish);

        //新增口味并绑定菜品
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors != null && flavors.size() > 0) {
            flavors.forEach(dishFlavor -> dishFlavor.setDishId(dish.getId()));
        }
        dishFlavorMapper.insertFlavor(flavors);
        //删除redis中缓存的当前分类的所有菜品
        log.info("删除redis中缓存的当前分类的所有菜品");
        stringRedisTemplate.delete("dish:cache:"+dishDTO.getCategoryId());
    }

    /**
     * 分页查询
     *
     * @param dishPageQueryDTO
     * @return
     */
    @Override
    public PageResult pageQuery(DishPageQueryDTO dishPageQueryDTO) {
        //1.设置分页参数
        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());
        //2.查询集合
        List<Dish> dishList = dishMapper.pageQuery(dishPageQueryDTO);
        Page<Dish> list = (Page<Dish>) dishList;
        //封装结果并返回
        return new PageResult(list.getTotal(), list.getResult());
    }

    @Override
    public void enableOrDisable(Integer status, Long id) {
        Dish dish = new Dish();
        dish.setId(id);
        dish.setStatus(status);
        dishMapper.update(dish);
        log.info("删除redis中所有菜品缓存");
        Set<String> keys = stringRedisTemplate.keys("dish:cache:*");
        if(keys != null){
            stringRedisTemplate.delete(keys);
        }
    }

    /**
     * 根据id查询
     *
     * @param id
     * @return
     */
    @Override
    public DishVO getById(Long id) {
        //1.查询菜品
        Dish dish = dishMapper.getById(id);
        //根据菜品id查询口味
        List<DishFlavor> dishFlavorList = dishFlavorMapper.getByDishId(id);
        //封装菜品口味并返回
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish, dishVO);
        dishVO.setFlavors(dishFlavorList);
        return dishVO;
    }

    /**
     * 修改菜品
     *
     * @param dishDTO
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void update(DishDTO dishDTO) {
        //1.修改菜品
        Dish dish = new Dish();

        BeanUtils.copyProperties(dishDTO, dish);
        dishMapper.update(dish);
        //修改口味-先删再插入
        dishFlavorMapper.deleteByDishId(dish.getId());
        //插入
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors != null && flavors.size() > 0) {
            flavors.forEach(dishFlavor -> dishFlavor.setDishId(dish.getId()));
        }
        if(flavors != null){
            dishFlavorMapper.insertFlavor(flavors);
        }
        log.info("删除redis中所有菜品缓存");
        Set<String> keys = stringRedisTemplate.keys("dish:cache:*");
        if(keys != null){
            stringRedisTemplate.delete(keys);
        }
    }

    /**
     * 批量删除
     *
     * @param ids
     */
    @Override
    public void delete(List<Long> ids) {
        //批量删除菜品
        //1.判断是否在售或与套餐关联
        ids.forEach(id -> {
            Dish dish = dishMapper.getById(id);
            if (Objects.equals(dish.getStatus(), StatusConstant.ENABLE)) {
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        });
        //2.判断当前菜品是否被套餐关联了
        List<Long> list = setmealMapper.selectByDishId(ids);
        if (!CollectionUtils.isEmpty(list)) {
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }
        //3.删除菜品和口味
        //3.1删除菜品
        ids.forEach(
                id -> {
                    dishMapper.deleteById(id);
                    dishFlavorMapper.deleteByDishId(id);
                }
        );
        log.info("删除redis中所有菜品缓存");
        Set<String> keys = stringRedisTemplate.keys("dish:cache:*");
        if(keys != null){
            stringRedisTemplate.delete(keys);
        }
    }


    /**
     * 根据分类id查询菜品
     *
     * @param categoryId
     * @return
     */
    @Override
    public List<Dish> list(Long categoryId) {
        return dishMapper.list(categoryId);
    }
}
